// pages/goods_list/index.js
import { request } from "../../request/index.js";
import regeneratorRuntime from '../../lib/runtime/runtime';
Page({
    data: {
        tabs: [{
                id: 0,
                value: "综合",
                isActive: true
            },
            {
                id: 1,
                value: "销量",
                isActive: false
            },
            {
                id: 2,
                value: "价格",
                isActive: false
            }
        ],
        goodsList: []
    },
    //接口要的参数
    QueryParams: {
        query: "",
        cid: "",
        pagenum: 1,
        pagesize: 10

    },
    //总页数
    totalPages: 1,


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        //cid或者query任选一个
        this.QueryParams.cid = options.cid || "";
        this.QueryParams.query = options.query || "";
        this.getGoodsList();

    },

    //获取商品列表数据
    async getGoodsList() {
        const res = await request({ url: "/goods/search", data: this.QueryParams });
        //获取中条数
        const total = res.total;
        //计算页数
        this.totalPages = Math.ceil(total / this.QueryParams.pagesize);
        // console.log(this.totalPages);

        this.setData({
            goodsList: [...this.data.goodsList, ...res.goods]
        });
        //关闭下拉刷新窗口
        wx.stopPullDownRefresh();


    },

    //标题点击事件
    handleTabsItemChange(e) {
        // 1 获取被点击标题索引
        const { index } = e.detail;
        // 修改原数组
        let { tabs } = this.data;
        tabs.forEach((v, i) => i === index ? v.isActive = true : v.isActive = false);
        //赋值到data
        this.setData({
            tabs
        })
    },

    //页面上滑
    onReachBottom() {
        //判断还有没有下一页数据
        if (this.QueryParams.pagenum >= this.totalPages) {
            //没有下一页数据
            // console.log("无下一页数据");
            wx.showToast({ title: '没有下一页数据' });

        } else {
            //没有下一页数据
            // console.log("有下一页数据");
            this.QueryParams.pagenum++;
            this.getGoodsList();

        }
    },
    //下拉刷新事件
    onPullDownRefresh() {
        //重置数组
        this.setData({
                goodsList: []
            })
            //重置页码
        this.QueryParams.pagenum = 1;
        //发送请求
        this.getGoodsList();

    }
})